package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.entity.Event;
import com.example.demo.service.EventService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/event")
public class EventController {

    @Resource
    private EventService eventService;

    @GetMapping("/list")
    public Result list(){
        PageInfo<Event> eventList = eventService.list();
        if(eventList != null){
            return Result.success(eventList);
        }
        else {
            return Result.error("事件列表为空!");
        }
    }
    @GetMapping("/listByParams")
    public Result listByParams(@RequestParam Integer currentPage, @RequestParam Integer pageSize,
                               @RequestParam(required = false) String startDate,@RequestParam(required = false) String endDate){
        PageInfo<Event> eventList = eventService.listByParams(currentPage,pageSize,startDate,endDate);
        if(eventList != null){
            return Result.success(eventList);
        }
        else {
            return Result.error("事件列表为空!");
        }
    }

    @GetMapping("/num")
    public Result num(){
        return Result.success(eventService.list().getSize());
    }

    @PostMapping("/addEvent")
    public Result addEvent(@RequestBody Event event, HttpSession session) {
        if(eventService.addEvent(event, session) != 1){
            return Result.error("事件添加失败");
        }
        return Result.success();
    }

    @PostMapping("/changeEvent")
    public Result changeEvent(@RequestBody Event event){
        if(eventService.changeEvent(event)){
            return Result.success();
        }
        else {
            return Result.error("更新失败!");
        }
    }

    @GetMapping("/findById")
    public Result findEventById(@RequestParam Integer id){
        Event event = eventService.getEventById(id);
        if(event != null){
            return Result.success(event);
        }
        else return Result.error("未查询到事件信息!");
    }

    @DeleteMapping("/deleteById")
    public Result deleteEventById(@RequestParam Integer id){
        if(eventService.deleteEventById(id)){
            return Result.success();
        }
        else return Result.error("删除失败!");
    }

    @PostMapping("/status")
    public Result updateStatus(@RequestParam Integer id){
        Event event = eventService.getEventById(id);
        if(event != null){
            if(event.getStatus() != 2){
                eventService.updateStatus(id);
                return Result.success();
            }
            return Result.error("状态已经最新!");
        }
        else{
            return Result.error("更新失败!");
        }
    }
}
